<script setup name="BusinessInterface">
import { CirclePlus, Delete, EditPen, View } from '@element-plus/icons-vue'
import { pcaTextArr } from 'element-china-area-data'
import Message from 'vue-m-message'
import { nextTick, reactive } from 'vue'
import businessInterfaceService from '@/api/businessInterface/index.js'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useDict } from '@/utils/dict.js'

const interfaceFormRef = ref(null)
// 显示参数或排序
const isCS = ref(false)
const isPX = ref(false)
// 新增参数列表
const paramList = ref([])
// 弹窗
const interfaceVisible = ref(false)
// 查看禁用
const form = ref({})
// 是否显示表格
const isTable = ref(false)
const isView = ref(false)
const tableData = ref([])
const customerName = ref([])
const queryParam = ref({})
const ids = ref([])
const btnLoad = ref(false)
const updateDialogTitle = ref('')
const { proxy } = getCurrentInstance()
const { sys_interface_param_type, sys_interface_type } = useDict(
  'invoice_type',
  'sys_interface_param_type',
  'sys_interface_type',
)

const searchConfig = reactive([
  {
    label: '所属流程',
    field: 'flowId',
    type: 'input',
    defaultShow: true,
  },
  {
    label: '接口名称',
    field: 'interfaceName',
    type: 'input',
    defaultShow: true,
  },
])

const tableColumns = reactive([
  { type: 'checkbox', width: 50 },

  {
    field: 'flowId',
    title: '所属流程',
    align: 'center',
    minWidth: 200,
    showOverflow: 'tooltip',
  },
  {
    field: 'interfaceName',
    title: '接口名称',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 120,
    showOverflow: 'tooltip',
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 200,
    fixed: 'right',
    slots: { default: 'operate' },
  },
])
const interfaceColumns = reactive([
  {
    field: 'paramName',
    title: '参数名称',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramName' },
  },
  {
    field: 'paramValue',
    title: '传值',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramValue' },
  },
  {
    field: 'paramKey',
    title: '参数key',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramKey' },
  },
  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 150,
    slots: { default: 'remark' },
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 150,
    slots: { default: 'operate' },
  },
])
const interfaceColumns1 = reactive([
  {
    field: 'paramName',
    title: '参数名称',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramName' },
  },
  {
    field: 'paramValue',
    title: '传值',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramValue' },
  },
  {
    field: 'paramOrder',
    title: '排序',
    align: 'center',
    minWidth: 150,
    slots: { default: 'paramOrder' },
  },

  {
    field: 'remark',
    title: '备注',
    align: 'center',
    minWidth: 150,
    slots: { default: 'remark' },
  },
  {
    field: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 150,
    slots: { default: 'operate' },
  },
])

// 申请开票
const rules = ref({
  interfaceId: [
    { required: true, message: '业务接口表不能为空', trigger: 'blur' },
  ],
  flowId: [{ required: true, message: '所属流程不能为空', trigger: 'blur' }],
  interfaceName: [
    { required: true, message: '接名称不能为空', trigger: 'blur' },
  ],
  interfaceType: [
    { required: true, message: '接口类型不能为空', trigger: 'change' },
  ],
  interfacePath: [
    { required: true, message: '接口路径不能为空', trigger: 'blur' },
  ],
  paramType: [
    {
      required: true,
      message: '接口参数类型不能为空',
      trigger: 'change',
    },
  ],
  paramName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
  paramValue: [{ required: true, message: '传值不能为空', trigger: 'blur' }],
  paramKey: [{ required: true, message: '参数key不能为空', trigger: 'blur' }],
  paramOrder: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})

const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

onMounted(() => {
  getList()
})

function getList() {
  const formData = {
    ...queryParam.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
  }
  btnLoad.value = true
  businessInterfaceService.list(formData).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    btnLoad.value = false
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange({ checked, records, reserves }) {
  const res = records.map(item => item.interfaceId)
  if (reserves.length > 0) {
    if (checked) {
      ids.value.push(...res)
    }
    else {
      const customerIdSet = new Set(reserves.map(item => item.interfaceId))
      ids.value = ids.value.filter(item => customerIdSet.has(item))
    }
  }
  else {
    ids.value = res
  }
}

function handleSearch(e, type) {
  if (type === 'reset') {
    customerName.value = []
  }
  queryParam.value = {
    locationArea: customerName.value.join('/'),
    registerDateMin: e.registDate
      ? `${formatDate(e.registDate[0], 'YYYY-MM-DD')}`
      : null,
    registerDateMax: e.registDate
      ? `${formatDate(e.registDate[1], 'YYYY-MM-DD')}`
      : null,
    ...e,
  }
  delete queryParam.value.registDate
  getList()
}

function handleReset() {
  interfaceVisible.value = false
}

// 删除
function handleDelete(row) {
  console.log(row, ids.value, 'id')
  const interfaceIds = row || ids.value
  console.log(interfaceIds, 'interfaceIds')
  businessInterfaceService.delete(interfaceIds).then((res) => {
    const { code } = res
    if (code === 200) {
      Message.success('删除成功')
      getList()
    }
  })
}

// 显示表格
function interfaceTypeChange(val) {
  console.log(val, 'paramType')
  if (val !== '') {
    isTable.value = true
  }
  else {
    isTable.value = false
  }
  if (val === 'body' || val === 'param') {
    isCS.value = true
    isPX.value = false
  }
  else if (val == 'path') {
    isPX.value = true
    isCS.value = false
  }
}
// 导出
function handleExport() {
  proxy.download(
    'system/businessInterface/export',
    { ...queryParam.value, exportIds: ids.value.join(',') },
    `businessInterface_${new Date().getTime()}.xlsx`,
  )
}

// 表单重置
function reset() {
  form.value = {
    interfaceId: undefined,
    flowId: undefined,
    interfaceName: undefined,
    interfaceType: undefined,
    interfacePath: undefined,
    paramType: undefined,
    remark: undefined,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    interfaceParams: [],
  }
  // resetForm("form");
}

// 新增
function handleAdd() {
  reset()
  paramList.value = []
  isTable.value = false
  interfaceVisible.value = true
  isView.value = false
  updateDialogTitle.value = '新增'
}

/** 修改按钮操作 */
function handleUpdate(row, View) {
  isView.value = View
  console.log(isView.value, View, 'row')
  interfaceTypeChange(row.paramType)
  updateDialogTitle.value = View ? '查看' : '修改'
  reset()
  const interfaceId = row.interfaceId || ids.value
  businessInterfaceService.getDetail(interfaceId).then((response) => {
    form.value = response.data
    paramList.value = response.data.interfaceParams
    interfaceVisible.value = true
  })
}

// 新增参数
function handleAddInfo() {
  const cell = {
    paramId: '',
    paramName: '',
    paramKey: '',
    paramValue: '',
    paramOrder: '',
    remark: '',
  }
  nextTick(() => {
    paramList.value.push(cell)
  })
}

// 删除参数
function handleDeleteInfo(data, index) {
  nextTick(() => {
    paramList.value.splice(index, 1)
  })
}

// 提交新增修改
function submitForm() {
  interfaceFormRef.value.validate((valid) => {
    if (valid) {
      if (form.value.interfaceId != null) {
        businessInterfaceService
          .update(form.value)
          .then((response) => {
            if (response.code == 200) {
              Message.success('修改成功')
              interfaceVisible.value = false
              getList()
            }
          })
          .finally(() => {})
      }
      else {
        form.value.interfaceParams = paramList.value
        businessInterfaceService
          .add(form.value)
          .then((response) => {
            if (response.code == 200) {
              Message.success('新增成功')
              interfaceVisible.value = false
              getList()
            }
          })
          .finally(() => {})
      }
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-3">
      <SearchBar :search-config="searchConfig" @search="handleSearch">
        <template #customerName>
          <el-cascader
            v-model="customerName"
            :options="pcaTextArr"
            size="default"
            placeholder="请选择所属区域"
            clearable
            class="w-full"
          />
        </template>
      </SearchBar>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar flex mb-1">
        <div class="mb-2 space-x-3">
          <el-button
            v-hasPermi="['system:businessInterface:add']"
            type="primary"
            @click="handleAdd"
          >
            新增
            <el-icon class="el-icon--right">
              <CirclePlus />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:zlPrompt:remove']"
            type="danger"
            class="el-gradient-danger"
            :disabled="ids.length === 0"
            @click="handleDelete(null)"
          >
            删除
            <el-icon class="el-icon--right">
              <Delete />
            </el-icon>
          </el-button>
          <el-button
            v-hasPermi="['system:finance:zlPrompt:export']"
            type="warning"
            class="el-gradient-warning"
            @click="handleExport()"
          >
            导出
            <el-icon class="el-icon--right">
              <FolderAdd />
            </el-icon>
          </el-button>
        </div>
        <RightToolbar />
      </div>
      <vxe-grid
        :data="tableData"
        :row-config="{
          keyField: 'interfaceId',
        }"
        :columns="tableColumns"
        :pager-config="pagerConfig"
        :column-config="{ resizable: true }"
        header-cell-class-name="headerCellClass"
        :loading="btnLoad"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
        max-height="650px"
      >
        <template #operate="{ row }">
          <el-button
            v-hasPermi="['system:businessInterface:query']"
            text
            type="success"
            size="small"
            @click="handleUpdate(row, true)"
          >
            查看
          </el-button>
          <el-button
            v-hasPermi="['system:businessInterface:edit']"
            text
            type="primary"
            size="small"
            @click="handleUpdate(row, false)"
          >
            修改
          </el-button>

          <span v-hasPermi="['system:businessInterface:remove']">
            <el-popconfirm
              title="确认删除吗？"
              width="200px"
              @confirm="handleDelete(row.interfaceId)"
            >
              <template #reference>
                <el-button text size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </vxe-grid>
    </el-card>

    <!-- 添加或修改业务流程接口对话框 -->
    <el-dialog
      v-model="interfaceVisible"
      width="60%"
      :destroy-on-close="true"
      class="custom-dialog"
      @close="handleReset"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px] ml-2">
            {{ updateDialogTitle }}
          </span>
        </div>
      </template>
      <el-form
        ref="interfaceFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="isView"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属流程" prop="flowId">
              <el-input v-model="form.flowId" placeholder="请输入所属流程" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="接口复用" prop="">
              <el-input
                v-model="form.interfaceId"
                placeholder="请输入接口复用"
              />
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="接口名称" prop="interfaceName">
              <el-input
                v-model="form.interfaceName"
                placeholder="请输入接口名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口路径" prop="interfacePath">
              <el-input
                v-model="form.interfacePath"
                placeholder="请输入接口路径"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="参数类型" prop="paramType">
              <el-select
                v-model="form.paramType"
                placeholder="请选择接口参数类型"
                @change="interfaceTypeChange($event)"
              >
                <el-option
                  v-for="dict in sys_interface_param_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口类型" prop="interfaceType">
              <el-select
                v-model="form.interfaceType"
                placeholder="请选择接口类型"
              >
                <el-option
                  v-for="dict in sys_interface_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form v-if="isTable" label-width="120px" :disabled="isView">
          <div style="margin-bottom: 15px">
            <el-button type="primary" plain @click="handleAddInfo">
              新增参数
              <el-icon class="el-icon--right">
                <CirclePlus />
              </el-icon>
            </el-button>
          </div>
          <vxe-grid :data="paramList" header-cell-class-name="headerCellContractClass" :columns="isCS == true ? interfaceColumns : interfaceColumns1" border>
            <template #paramName="{ row }">
              <el-input
                v-model="row.paramName"
                placeholder="请输入参数名称"
                clearable
                :min="0"
              />
            </template>
            <template #paramValue="{ row }">
              <el-input
                v-model.number="row.paramValue"
                placeholder="请输入传值"
                clearable
                :min="0"
                style="flex: 1"
              />
            </template>
            <template #paramKey="{ row }">
              <el-input
                v-model="row.paramKey"
                placeholder="请输入参数key"
                clearable
                :min="0"
              />
            </template>

            <template #paramOrder="{ row }">
              <el-input
                v-model.number="row.paramOrder"
                placeholder="请输入排序"
                clearable
                :min="0"
                style="flex: 1"
              />
            </template>
            <template #remark="{ row }">
              <el-input
                v-model.number="row.remark"
                placeholder="请输入备注"
                clearable
                :min="0"
                style="flex: 1"
              />
            </template>
            <template #operate="{ row }">
              <el-button
                type="danger"
                size="small"
                plain
                @click="handleDeleteInfo(row, $index)"
              >
                删除
              </el-button>
            </template>
          </vxe-grid>
          <!-- <el-table
            ref="tb"
            :data="paramList"
            :header-cell-style="{
              background: '#cce8eb',
              border: '1px solid #eeeeee',
              color: '#0E6CFF',
            }"
            border
          >
            <el-table-column prop="paramName" label="参数名称" align="center">
              <template #default="scope">
                <el-input
                  v-model="scope.row.paramName"
                  placeholder="请输入参数名称"
                  clearable
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paramValue" label="传值" align="center">
              <template #default="scope">
                <el-input
                  v-model.number="scope.row.paramValue"
                  placeholder="请输入传值"
                  clearable
                  :min="0"
                  style="flex: 1"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="isCS"
              prop="paramKey"
              label="参数key"
              align="center"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.paramKey"
                  placeholder="请输入参数key"
                  clearable
                  :min="0"
                />
              </template>
            </el-table-column>

            <el-table-column
              v-if="isPX"
              prop="paramOrder"
              label="排序"
              align="center"
            >
              <template #default="scope">
                <el-input
                  v-model.number="scope.row.paramOrder"
                  placeholder="请输入排序"
                  clearable
                  :min="0"
                  style="flex: 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center">
              <template #default="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  clearable
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" width="200" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDeleteInfo(scope.row, scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table> -->
        </el-form>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">
            确 定
          </el-button>
          <el-button @click="interfaceVisible = false">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.dialog-header {
  width: 188px;
  height: 0;
  border-width: 0px 45px 45px 0px;
  border-style: none solid solid;
  border-color: transparent transparent var(--el-color-primary);
  color: #fff;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  padding: 20px 10px 10px 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
::v-deep(.el-tabs__nav) {
  width: 100% !important;

  .el-tabs__item {
    width: 33%;
  }
}
</style>
